package com.rxyb.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxyb.authority.constants.AuthorityConstants;
import com.rxyb.authority.db.dao.OpsAuthorityUserMapper;
import com.rxyb.authority.db.po.OpsAuthorityUser;
import com.rxyb.authority.gateway.dto.role.GetRoleInfoReq;
import com.rxyb.authority.gateway.dto.role.GetRoleInfoRsp;
import com.rxyb.authority.gateway.dto.user.*;
import com.rxyb.authority.service.OpsAuthorityRoleService;
import com.rxyb.authority.service.OpsAuthorityUserService;
import com.rxyb.core.respone.R;
import com.rxyb.core.respone.enums.CommonCode;
import com.rxyb.redis.utils.RedisStringUtils;
import com.rxyb.security.password.MD5PasswordEncode;
import com.rxyb.toolize.VO;
import com.rxyb.toolize.date.DateTime;
import com.rxyb.toolize.date.enums.FormatDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DUYH
 * @since 2020-05-29
 */
@Service
public class OpsAuthorityUserServiceImpl extends ServiceImpl<OpsAuthorityUserMapper, OpsAuthorityUser> implements OpsAuthorityUserService {

    @Autowired(required = false)
    private RedisStringUtils redisStringUtils;
    @Autowired(required = false)
    private OpsAuthorityUserMapper opsAuthorityUserMapper;
    @Autowired(required = false)
    private OpsAuthorityRoleService opsAuthorityRoleService;

    @Override
    public R<LoginRsp> login(LoginReq loginReq) {

        final Optional<String> optional = redisStringUtils.get("menuGorup", "menuKey");
        if (optional.isPresent()) {
            System.out.println("获取REDIS数据===>" + optional.get());
        } else {
            System.out.println("获取REDIS数据===>失败，重新插入");
            redisStringUtils.set("menuGorup", "menuKey", DateTime.getDateTime(FormatDate.FORMAT_TIME_HOUR_MINUTE_SECOND), TimeUnit.MINUTES, 5);
        }
        // 查询用户信息
        QueryWrapper<OpsAuthorityUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityUser::getLoginName, loginReq.getLoginName()).or().eq(OpsAuthorityUser::getUserName, loginReq.getLoginName()).or().eq(OpsAuthorityUser::getUserMobile, loginReq.getLoginName()).or().eq(OpsAuthorityUser::getUserEmail, loginReq.getLoginName()).or().eq(OpsAuthorityUser::getOpenId, loginReq.getLoginName());
        OpsAuthorityUser record = opsAuthorityUserMapper.selectOne(wrapper);
        System.out.println("OpsAuthorityUserServiceImpl.login==>record....." + record);
        if (record != null) {
            LoginRsp loginRsp = new LoginRsp();
            BeanUtils.copyProperties(record, loginRsp);
            // 查询角色信息
            GetRoleInfoReq getRoleInfoReq = new GetRoleInfoReq();
            getRoleInfoReq.setRoleId(record.getRoleId());
            System.out.println("opsAuthorityRoleService==>" + opsAuthorityRoleService);
            R<GetRoleInfoRsp> r = opsAuthorityRoleService.query(getRoleInfoReq);
            if (r.ok()) {
                LoginRoleRsp loginRoleRsp = new LoginRoleRsp();
                BeanUtils.copyProperties(r.getData(), loginRoleRsp);
                List<LoginRoleRsp> roleList = new ArrayList<>();
                roleList.add(loginRoleRsp);
                loginRsp.setRoleList(roleList);
                return R.ok(loginRsp);
            } else {
                throw new UsernameNotFoundException("角色为空或已失效");
            }
        }
        return R.failed(CommonCode.USER_NOT_EXIST);
    }

    /**
     * 创建用户
     *
     * @author duyh
     */
    @Override
    public R<CreateUserRsp> create(CreateUserReq createUserReq) {
        // 验证用户各个条件是否已存在
        R<CreateUserRsp> notExsit = isNotExsit(createUserReq);
        if (!notExsit.ok()) {
            return notExsit;
        }
        OpsAuthorityUser record = new OpsAuthorityUser();
        BeanUtils.copyProperties(createUserReq, record);
        record.setRowState(AuthorityConstants.ROWSTATE_NORMAL);
        record.setAddTime(DateTime.getDateTime());
        record.setUpdateTime(DateTime.getDateTime());
        int cnt = opsAuthorityUserMapper.insert(record);
        if (cnt == 1) {
            CreateUserRsp createUserRsp = new CreateUserRsp();
            createUserRsp.setId(record.getId());
            createUserRsp.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
            return R.ok(createUserRsp);
        }
        return R.failed(CommonCode.FAILED);
    }

    /**
     * 用户详情
     *
     * @author duyh
     */
    @Override
    @Cacheable(cacheNames = {"user"}, key = "#getUserInfoReq.getId()", unless = "#result == null")
    public R<GetUserInfoRsp> query(GetUserInfoReq getUserInfoReq) {
        QueryWrapper<OpsAuthorityUser> wrapper = new QueryWrapper<>();
        if (null != getUserInfoReq.getId()) {
            wrapper.lambda().eq(OpsAuthorityUser::getId, getUserInfoReq.getId());
        }
        wrapper.lambda().eq(OpsAuthorityUser::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        List<OpsAuthorityUser> opsAuthorityUsers = opsAuthorityUserMapper.selectList(wrapper);
        OpsAuthorityUser record = null;
        if (null != opsAuthorityUsers && opsAuthorityUsers.size() == 1) {
            record = opsAuthorityUsers.get(0);
        }
        if (null == record) {
            return R.failed(CommonCode.USER_NOT_EXIST);
        }
        GetUserInfoRsp getUserInfoRsp = new GetUserInfoRsp();
        BeanUtils.copyProperties(record, getUserInfoRsp);
        getUserInfoRsp.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
        getUserInfoRsp.setUpdateTime(DateTime.getDateFormat(record.getUpdateTime(), FormatDate.FORMAT_TIME_STR));
        return R.ok(getUserInfoRsp);
    }

    /**
     * 修改用户通过ID
     *
     * @author duyh
     */
    @Override
    @CachePut(value = "user", key = "#updateUserReq.getId()")
    public R<UpdateUserRsp> updateById(UpdateUserReq updateUserReq) {
        OpsAuthorityUser record = new OpsAuthorityUser();
        record.setId(updateUserReq.getId());
        record.setUpdateTime(DateTime.getDateTime());
        // 需要修改的参数
        record.setUserName(updateUserReq.getUserName());
        record.setUserEmail(updateUserReq.getUserEmail());
        record.setUserMobile(updateUserReq.getUserMobile());
        record.setRoleId(updateUserReq.getRoleId());
        record.setUserState(updateUserReq.getUserState());
        record.setNeedUpdate(updateUserReq.getNeedUpdate());
        int cnt = opsAuthorityUserMapper.updateById(record);
        if (cnt == 1) {
            return R.ok(new UpdateUserRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    /**
     * 删除用户
     *
     * @author duyh
     */
    @Override
    @CacheEvict(value = "user", key = "#deleteUserReq.getId()")
    public R<DeleteUserRsp> remove(DeleteUserReq deleteUserReq) {
        // 需要修改的参数
        OpsAuthorityUser record = new OpsAuthorityUser();
        record.setId(deleteUserReq.getId());
        record.setRowState(AuthorityConstants.ROWSTATE_DELETE);
        record.setUpdateTime(DateTime.getDateTime());
        int cnt = opsAuthorityUserMapper.updateById(record);
        if (cnt == 1) {
            return R.ok(new DeleteUserRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    /**
     * 用户列表
     *
     * @author duyh
     */
    @Override
    public R<GetUserListRsp> list(GetUserListReq getUserListReq) {
        List<AuthorityUserVo> resultList = new ArrayList<>();
        QueryWrapper<OpsAuthorityUser> wrapper = new QueryWrapper<>();
        // 按照检车站搜索
        if (null != getUserListReq.getRoleId()) {
            wrapper.lambda().eq(OpsAuthorityUser::getRoleId, getUserListReq.getRoleId());
        }
        // 按照检车站搜索
        if (VO.isNotBlank(getUserListReq.getOrgId())) {
            wrapper.lambda().eq(OpsAuthorityUser::getOrgId, getUserListReq.getOrgId());
        }
        // 按照登录名搜索
        if (VO.isNotBlank(getUserListReq.getLoginName())) {
            wrapper.lambda().like(OpsAuthorityUser::getLoginName, "%" + getUserListReq.getLoginName().trim() + "%");
        }
        // 按照用户名搜索
        if (VO.isNotBlank(getUserListReq.getUserName())) {
            wrapper.lambda().like(OpsAuthorityUser::getUserName, "%" + getUserListReq.getUserName().trim() + "%");
        }
        // 按照手机号搜索
        if (VO.isNotBlank(getUserListReq.getUserMobile())) {
            wrapper.lambda().like(OpsAuthorityUser::getUserMobile, "%" + getUserListReq.getUserMobile().trim() + "%");
        }
        // 按照是否有效搜索
        if (null != getUserListReq.getUserState() && getUserListReq.getUserState() != 0) {
            wrapper.lambda().eq(OpsAuthorityUser::getUserState, getUserListReq.getUserState());
        }
        wrapper.lambda().eq(OpsAuthorityUser::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 排序
        wrapper.orderByDesc("update_time");

        //总页数+总记录数
        Page<OpsAuthorityUser> page = new Page<>(getUserListReq.getPageNo(), getUserListReq.getPageSize());
        IPage<OpsAuthorityUser> iPage = opsAuthorityUserMapper.selectPage(page, wrapper);
        List<OpsAuthorityUser> list = iPage.getRecords();
        if (list != null && list.size() != 0) {
            for (OpsAuthorityUser record : list) {
                AuthorityUserVo user = new AuthorityUserVo();
                BeanUtils.copyProperties(record, user);
                user.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
                user.setUpdateTime(DateTime.getDateFormat(record.getUpdateTime(), FormatDate.FORMAT_TIME_STR));
                resultList.add(user);
            }
        }
        GetUserListRsp getUserListRsp = new GetUserListRsp();
        getUserListRsp.setSize(iPage.getTotal());
        getUserListRsp.setList(resultList);
        return R.ok(getUserListRsp);
    }


    /**
     * 密码修改
     */
    @Override
    @CacheEvict(value = "user", key = "#updatePwdReq.getId()")
    public R<UpdatePwdRsp> updatePwd(UpdatePwdReq updatePwdReq) {
        OpsAuthorityUser record = new OpsAuthorityUser();
        record.setId(updatePwdReq.getId());
        record.setUpdateTime(DateTime.getDateTime());
        record.setNeedUpdate(AuthorityConstants.NO);
        record.setLoginPwd(new MD5PasswordEncode().encode(updatePwdReq.getLoginPwd()));
        int cnt = opsAuthorityUserMapper.updateById(record);
        if (cnt == 1) {
            return R.ok(new UpdatePwdRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    /**
     * 用户是否存在
     */
    private R<CreateUserRsp> isNotExsit(CreateUserReq createUserReq) {
        QueryWrapper<OpsAuthorityUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityUser::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        if (VO.isNotBlank(createUserReq.getLoginName())) {
            wrapper.lambda().or().eq(OpsAuthorityUser::getLoginName, createUserReq.getLoginName());
        }
        if (VO.isNotBlank(createUserReq.getUserName())) {
            wrapper.lambda().or().eq(OpsAuthorityUser::getUserName, createUserReq.getUserName());
        }
        if (VO.isNotBlank(createUserReq.getUserEmail())) {
            wrapper.lambda().or().eq(OpsAuthorityUser::getUserEmail, createUserReq.getUserEmail());
        }
        if (VO.isNotBlank(createUserReq.getUserMobile())) {
            wrapper.lambda().or().eq(OpsAuthorityUser::getUserMobile, createUserReq.getUserMobile());
        }
        if (VO.isNotBlank(createUserReq.getOpenId())) {
            wrapper.lambda().or().eq(OpsAuthorityUser::getOpenId, createUserReq.getOpenId());
        }
        List<OpsAuthorityUser> opsAuthorityUsers = opsAuthorityUserMapper.selectList(wrapper);
        if (opsAuthorityUsers.size() > 0) {
            for (OpsAuthorityUser opsAuthorityUser : opsAuthorityUsers) {
                if (VO.isNotBlank(createUserReq.getLoginName()) && createUserReq.getLoginName().equals(opsAuthorityUser.getLoginName())) {
                    return R.failed(CommonCode.USER_LOGIN_EXIST);
                } else if (VO.isNotBlank(createUserReq.getUserName()) && createUserReq.getUserName().equals(opsAuthorityUser.getUserName())) {
                    return R.failed(CommonCode.USER_LOGIN_EXIST);
                } else if (VO.isNotBlank(createUserReq.getUserEmail()) && createUserReq.getUserEmail().equals(opsAuthorityUser.getUserEmail())) {
                    return R.failed(CommonCode.USER_LOGIN_EXIST);
                } else if (VO.isNotBlank(createUserReq.getUserMobile()) && createUserReq.getUserMobile().equals(opsAuthorityUser.getUserMobile())) {
                    return R.failed(CommonCode.USER_LOGIN_EXIST);
                } else if (VO.isNotBlank(createUserReq.getOpenId()) && createUserReq.getOpenId().equals(opsAuthorityUser.getOpenId())) {
                    return R.failed(CommonCode.USER_LOGIN_EXIST);
                }
            }
        }
        return R.ok(new CreateUserRsp());
    }

}
